package com.imooc;

import com.imooc.cofig.ResourceConfig;
import com.imooc.enums.BGMOperatorTypeEnum;
import com.imooc.utils.JsonUtils;
import org.apache.commons.io.FileUtils;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.File;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

/**
 * @author Zhou
 * @create 2020-12-03 15:14
 */
@Component
public class ZKCuratorClient {
//    @Autowired
//    private BgmService bgmService;

    @Autowired
    private ResourceConfig resourceConfig;
    //zk客户端
    private CuratorFramework client = null;
    final static Logger log = LoggerFactory.getLogger(ZKCuratorClient.class);

//    public static final String ZOOKEEPER_SERVER = "192.168.254.100:2181";


    public void init() {
        if (client != null){
            return;
        }
        //重试策略
        int baseSleepTimeMs = 1000;
        int maxRetries = 5;
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(baseSleepTimeMs, maxRetries);
        //创建客户端
        client = CuratorFrameworkFactory.builder()
                .connectString(resourceConfig.getZookeeperServer())
                .sessionTimeoutMs(10000).retryPolicy(retryPolicy)
                .namespace("admin").build();

        //启动客户端
        client.start();

        try {
//
//            String testNodeData = new String(client.getData().forPath("/bgm/201203808CYT51AW"));
//            log.info("the data for test is {}",testNodeData);
            addChildWatch("/bgm");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void addChildWatch(String nodePath) throws Exception {
        final PathChildrenCache cache = new PathChildrenCache(client, nodePath, true);
        cache.start();
        cache.getListenable().addListener(new PathChildrenCacheListener() {
            @Override
            public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
                if (event.getType().equals(PathChildrenCacheEvent.Type.CHILD_ADDED)){
                    log.info("监听到 CHILD_ADDED 事件");
                    //1. 从数据库查询Bgm对象，获取路径path
                    String path = event.getData().getPath();
                    String operatorObj = new String(event.getData().getData());

                    Map<String, String> map= JsonUtils.jsonToPojo(operatorObj, Map.class);
                    String operatorType = map.get("operType");
                    String songPath = map.get("path");

//                    String[] split = path.split("/");
//                    String bgmId = split[split.length - 1];
//                    Bgm bgm = bgmService.queryBgmById(bgmId);
//                    if (bgm == null){
//                        return;
//                    }
                    //1.1 bgm所在的相对路径
//                    String songPath = bgm.getPath();
                    //2.定义保存到本地路径
//                    String filePath = "D:\\programming\\imooc_video_dev" + songPath;
                    String filePath = resourceConfig.getFileSpace() + songPath;
                    //3.定义下载的路径（播放url）
                    String[] arrPath = songPath.split("\\\\");
                    String finalPath = "";
                    //3.1处理url斜杠以及编码
                    for (int i = 0; i < arrPath.length; i ++){
                        if (! StringUtils.isEmpty(arrPath[i])){
                            finalPath += "/";
                            finalPath += URLEncoder.encode(arrPath[i], "UTF-8");
                        }
                    }
//                    String bgmUrl = "http://192.168.1.114:8080/mvc" + finalPath;
                    String bgmUrl = resourceConfig.getBgmServer() + finalPath;

                    if (operatorType.equals(BGMOperatorTypeEnum.ADD.type)){
                        //下载bgm到springBoot服务器
                        URL url = new URL(bgmUrl);
                        File file = new File(filePath);
                        FileUtils.copyURLToFile(url, file);
                        client.delete().forPath(path);
                    }else if (operatorType.equals(BGMOperatorTypeEnum.DELETE.type)){
                        File file = new File(filePath);
                        FileUtils.forceDelete(file);
                        client.delete().forPath(path);
                    }
                }
            }
        });
    }
}
